package org.dromara.auth.strategy.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthToken;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.request.AuthWechatMiniProgramRequest;
import org.dromara.auth.domain.vo.LoginVo;
import org.dromara.auth.form.XcxLoginBody;
import org.dromara.auth.strategy.AbstractAuthStrategy;
import org.dromara.common.core.enums.LoginType;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.system.api.domain.vo.RemoteClientVo;
import org.dromara.common.core.domain.model.XcxLoginUser;
import org.dromara.system.api.services.SystemUserApiService;
import org.springframework.stereotype.Service;

import static org.dromara.common.core.enums.LoginType.XCX;

/**
 * 小程序认证策略
 *
 * @author shuai.zhou
 */
@Slf4j
@Service("xcxAuthStrategy")
@RequiredArgsConstructor
public class XcxAuthStrategy extends AbstractAuthStrategy {

    private final SystemUserApiService systemUserApiService;

    @Override
    public LoginVo login(String body, RemoteClientVo client) {
        XcxLoginBody loginBody = JsonUtils.parseObject(body, XcxLoginBody.class);
        ValidatorUtils.validate(loginBody);
        // xcxCode 为 小程序调用 wx.login 授权后获取
        String xcxCode = loginBody.getXcxCode();
        // 多个小程序识别使用
        String appid = loginBody.getAppid();

        // 校验 appid + appsrcret + xcxCode 调用登录凭证校验接口 获取 session_key 与 openid
        AuthRequest authRequest = new AuthWechatMiniProgramRequest(AuthConfig.builder()
            .clientId(appid).clientSecret("自行填写密钥 可根据不同appid填入不同密钥")
            .ignoreCheckRedirectUri(true).ignoreCheckState(true).build());
        AuthCallback authCallback = new AuthCallback();
        authCallback.setCode(xcxCode);
        AuthResponse<AuthUser> resp = authRequest.login(authCallback);
        String openid, unionId;
        if (resp.ok()) {
            AuthToken token = resp.getData().getToken();
            openid = token.getOpenId();
            // 微信小程序只有关联到微信开放平台下之后才能获取到 unionId，因此unionId不一定能返回。
            unionId = token.getUnionId();
        } else {
            throw new ServiceException(resp.getMsg());
        }
        // todo getUserInfoByOpenid 方法内部查询逻辑需要自行根据业务实现
        XcxLoginUser loginUser = systemUserApiService.getUserInfoByOpenId(openid);

        LoginVo loginVo = loginClient(client, loginUser);
        loginVo.setOpenid(openid);
        return loginVo;
    }

    @Override
    public LoginType loginType() {
        return XCX;
    }

}
